<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { userManageAPI, userVO } from "@/services/userManage";
import IconSearch from "@/assets/icons/IconSearch.vue";
import { debounce } from 'lodash-es';
import { ElMessage, ElMessageBox } from 'element-plus';

const userData = ref<userVO[]>([]);
const query = ref({ uname: "" });
const size = ref("15");
const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);

const showDetailDialog = ref(false);
const showAddDialog = ref(false);
const currentDetailData = ref<userVO | null>(null);

const formData = ref<userVO>({
  id: 0,
  uid: '',
  uname: '',
  email: '',
  phone: '',
  sex: '',
  birthday: new Date(),
  avatarUrl: '',
  description: '',
  isSinger: 0,
});

const options = [
  { value: "15", label: "15" },
  { value: "20", label: "20" },
  { value: "30", label: "30" },
  { value: "40", label: "40" },
  { value: "50", label: "50" },
];

const paginatedTableData = computed(() => userData.value);

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getData();
};

const handleSizeChange = (val: string) => {
  size.value = val;
  currentPage.value = 1;
  getData();
};

const handleViewDetail = (row: userVO) => {
  currentDetailData.value = { ...row };
  showDetailDialog.value = true;
};

const handleEdit = (row: userVO) => {
  formData.value = { ...row };
  showAddDialog.value = true;
};

const handleDelete = async (row: userVO) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await userManageAPI().deleteUser(row.id);
    ElMessage.success('删除成功');
    getData();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

const submitForm = async () => {
  try {
    if (formData.value.id) {
      await userManageAPI().updateUser(formData.value);
      ElMessage.success('更新成功');
    } else {
      await userManageAPI().addUser(formData.value);
      ElMessage.success('添加成功');
    }
    showAddDialog.value = false;
    getData();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

const handleSearch = debounce(() => {
  currentPage.value = 1;
  getData();
}, 500);

onMounted(() => {
  getData();
});

watch(() => query.value.uname, () => {
  handleSearch();
});

const getData = async () => {
  try {
    loading.value = true;
    const response = await userManageAPI().getUserByName(query.value.uname, currentPage.value, parseInt(size.value));
    userData.value = response.data.items;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取用户数据失败');
  } finally {
    loading.value = false;
  }
};

// Format functions for display
const formatPhone = (phone: string) => {
  if (!phone) return '无';
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};

const formatDate = (date: Date | string) => {
  if (!date) return '无';
  const d = new Date(date);
  return isNaN(d.getTime()) ? '无' : d.toLocaleDateString();
};

const formatDescription = (desc: string) => {
  if (!desc) return '无';
  return desc.length > 20 ? `${desc.substring(0, 20)}...` : desc;
};
</script>

<template>
  <div class="flex h-full gap-6">
    <div class="flex-1 bg-white rounded-lg p-4 flex flex-col justify-between min-w-0">
      <div class="flex items-center justify-between gap-8 mb-4 flex-wrap">
        <div class="flex gap-8 flex-wrap">
          <div>
            <el-input
              v-model="query.uname"
              class="input-grey"
              style="width: 200px"
              placeholder="输入用户名搜索"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <IconSearch class="w-4 h-4 cursor-pointer" />
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="paginatedTableData"
        style="width: 100%"
        height="85%"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
      >
        <el-table-column prop="uname" label="用户名" align="center" width="120">
          <template #default="{ row }">
            <span>{{ row.uname || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center">
          <template #default="{ row }">
            <span>{{ row.email || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" align="center" width="150">
          <template #default="{ row }">
            <span>{{ formatPhone(row.phone) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" width="80">
          <template #default="{ row }">
            <span>{{ row.sex || '未知' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生日" align="center" width="120">
          <template #default="{ row }">
            <span>{{ formatDate(row.birthday) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center" width="100">
          <template #default="{ row }">
            <el-avatar :src="row.avatarUrl" v-if="row.avatarUrl" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="isSinger" label="是否歌手" align="center" width="100">
          <template #default="{ row }">
            <span>{{ row.isSinger === 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center">
          <template #default="{ row }">
            <span>{{ formatDescription(row.description) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <div class="flex justify-center gap-6">
              <button class="text-[#005F59] text-[15px]" @click="handleEdit(scope.row)">编辑</button>
              <button class="text-[#FF2D55] text-[15px]" @click="handleDelete(scope.row)">删除</button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-[36px] flex items-center justify-between mt-6">
        <div>
          <span class="text-[#8a8a8f] text-sm mr-2">每页结果</span>
          <el-select
            v-model="size"
            placeholder="Select"
            style="width: 70px"
            class="input-grey"
            @change="handleSizeChange"
          >
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="parseInt(size)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <el-dialog v-model="showAddDialog" :title="formData.id ? '编辑用户' : '添加用户'" width="50%">
    <el-form :model="formData" label-width="100px">
      <el-form-item label="用户名" required>
        <el-input v-model="formData.uname" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formData.phone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="formData.sex" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker v-model="formData.birthday" type="date" placeholder="选择生日" />
      </el-form-item>
      <el-form-item label="头像 URL">
        <el-input v-model="formData.avatarUrl" placeholder="请输入头像链接" />
      </el-form-item>
      <el-form-item label="是否歌手">
        <el-switch v-model="formData.isSinger" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.icon {
  fill: currentColor;
  width: 20px;
  margin-right: 6px;
}
.input-grey {
  .el-input__wrapper {
    background: #f9f9f9;
    padding-left: 8px;
  }
  .el-select__wrapper {
    background: #f9f9f9;
  }
}
.el-table__header-wrapper {
  border-radius: 6px;
}
.table-header {
  background: #b88b7a !important;
  color: white;
  height: 50px !important;
  font-size: 15px;
  .el-table__cell {
    background: transparent !important;
    font-weight: 500;
  }
}
</style>